package com.xiaoyang.forum.common.exception;

import com.xiaoyang.forum.common.code.Result;
import com.xiaoyang.forum.common.code.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: XiaoYang
 * @CreateTime: 2025-08-10
 * @Description: 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public Result handleApplicationException (ApplicationException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        if (e.getErrorResult() != null) {
            return e.getErrorResult();
        }
        return Result.failed(e.getMessage());
    }
    /**
     * 处理全未捕获的其他异常
     * @param e Exception
     * @return AppResult
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result handleException (Exception e) {
        // 打印异常
        // e.printStackTrace();
        // 记录⽇志
        log.error(e.getMessage());
        if (e.getMessage() == null) {
            return Result.failed(ResultCode.ERROR_SERVICES);
        }
        return Result.failed(e.getMessage());
    }
}
